<template>
  <!-- 宿舍收费类型页面 -->
  <div class="app-container">
    <el-row>
     
    <el-form :model="queryParams" label-width="90px" ref="queryForm" :inline="true" v-show="showSearch">
        <el-col :span="6">
           <el-form-item label="年份" prop="year">
              <el-date-picker v-model="queryParams.year" type="year" value-format="yyyy" format="yyyy" placeholder="选择年">
              </el-date-picker>
            </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="专业">
            <el-select
                v-model="queryParams.sCode"
                placeholder="请选择专业"
                clearable
                filterable 
                style="width: 100%"
              >
                <el-option
                  v-for="(item,index) in typeList"
                  :key="index"
                  :label="item.name"
                  :value="item.sCode"
                ></el-option>
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收费类型" prop="feeType">
              <el-select
                v-model="queryParams.feeType"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.sys_charging_standards"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
              </el-form-item>
        </el-col>
        <el-col :span="6" style="float:right;text-align: right;">
          <el-form-item>
            <div>
              <el-button type="primary" icon="el-icon-search" @click="onSearch" size="mini">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
       <el-button
        type="warning"
        plain
        icon="el-icon-download"
        size="mini"
        @click="handleExport"
        >导出</el-button
      >
      </el-col> 
  
    <el-col :span="1.5">
       <el-button
            type="primary"
            plain
            size="mini"
            @click="upload.open = true"
            v-hasPermi="['departure:clrGradStuRoster:import']"
            >批量上传</el-button
          >
        </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table :data="roleList"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="年份" prop="year" align="center" />
      <el-table-column label="专业名称" prop="sName" align="center" />
      <el-table-column label="收费标准" prop="feeType" align="center">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_charging_standards"
            :value="scope.row.feeType"
          ></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="床位数" prop="bedNum" align="center">
      </el-table-column>
      <el-table-column label="已选床位数" prop="useBedNum" align="center">
        <template slot-scope="scope">
           <el-button size="mini" type="text" @click="handBedType(scope.row)"
            > {{ scope.row.useBedNum }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 专业列表添加或修改 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="60%"
      append-to-body
      @close="$refs['form'].resetFields()"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="年份" prop="year">
              <el-date-picker v-model="form.year" type="year" value-format="yyyy" format="yyyy" placeholder="选择年" :disabled="updatadisabled">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="sCode">
              <el-select
                v-model="form.sCode"
                placeholder="请选择专业"
                clearable
                filterable 
                style="width: 100%"
                @change="changeType" :disabled="updatadisabled"
              >
                <el-option
                  v-for="(item,index) in typeList"
                  :key="index"
                  :label="item.name"
                  :value="item.sCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收费类型" prop="feeType">
              <el-select
                v-model="form.feeType"
                placeholder="请选择"
                clearable
                style="width: 100%"
                :disabled="updatadisabled"
              >
                <el-option
                  v-for="dict in dict.type.sys_charging_standards"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="床位数" prop="bedNum">
              <el-input v-model.number="form.bedNum" maxlength="6" placeholder="请输入床位数"></el-input>

            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
     <!-- 批量导入书费退费 -->
    <el-dialog
      title="excel导入"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
       ref="uploads"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="onSuccess"
        :auto-upload="false"
      >
      <el-button size="small" type="text">选择文件</el-button>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="handleExportTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
     <el-dialog
      title="上传结果"
      :visible.sync="uploadData"
      width="500px"
      append-to-body
    >
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importData">下载上传结果</el-button>
        <el-button @click="uploadData = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
    title="查询宿舍收费类型明细"
    :visible.sync="openDlg"
    width="70%"
    append-to-body
    destroy-on-close
  >
   <el-form :model="classParams" ref="classForm" :inline="true">
      <el-form-item label="学生姓名">
        <el-input v-model="classParams.studentName" clearable placeholder="请输入学生姓名"></el-input>
      </el-form-item>
      <el-form-item label="注册号">
        <el-input v-model="classParams.registerCode" clearable placeholder="请输入学生注册号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="classQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="classReset"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-table :data="dataList">
      
      <el-table-column
        label="注册号"
        align="center"
        show-overflow-tooltip
        prop="registerCode"
      ></el-table-column>
      <el-table-column
        label="姓名"
        align="center"
        show-overflow-tooltip
        prop="studentName"
      ></el-table-column>
      <el-table-column
        label="性别"
        align="center"
        show-overflow-tooltip
        prop="sex"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"></dict-tag>
        </template>
      </el-table-column>
       
      <el-table-column
        label="所在院系"
        align="center"
        show-overflow-tooltip
        prop="college"
      ></el-table-column>
      <el-table-column
        label="班级"
        align="center"
        show-overflow-tooltip
        prop="className"
      ></el-table-column>
      <el-table-column
        label="专业"
        align="center"
        show-overflow-tooltip
        prop="specialityName"
      ></el-table-column>
      <el-table-column
        label="年级"
        align="center"
        show-overflow-tooltip
        prop="gradeName"
      ></el-table-column>
      <el-table-column label="收费标准" prop="feeType" align="center">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_charging_standards"
            :value="scope.row.feeType"
          ></dict-tag>
        </template>
      </el-table-column>
     
    </el-table>
    <!-- 修改了分页显示条件 -->
    <pagination
      v-show="dataTotal > 0"
      :total="dataTotal"
      :page.sync="classParams.pageNum"
      :limit.sync="classParams.pageSize"
      @pagination="getListDate"
      class="mt-4"
    />
      
  </el-dialog>
  </div>
</template>
<script>
import {
  feeTypeList,
  getFeeType,
  updateFeeType,
  putFeeType,
  delFeeType,
  feeTypeInfo
} from "@/api/apartment/feeType";
import searchForm from "@/components/Search/searchForm.vue";
import { specialityList } from "@/api/information/unitMajor";
import { getToken } from "@/utils/auth";

export default {
  dicts: ["sys_charging_standards",'sys_user_sex'],
  components: { searchForm },
  data() {
    return {
      tabPosition: "left",
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      dataList: [],
      openDlg:false,
      classParams:{
        studentName: '',
        registerCode: '',
          pageNum: 1,
        pageSize: 10,
        typeId: ''
      },
      dataTotal: 0,
      // 非单个禁用
      single: true,
      updatadisabled:false,
      uploadData:false,
      // 非多个禁用
      multiple: true,
        studenData: {},
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
       upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: true,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API + "/dorm/feeType/uploadTemplate",
      },

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      typeList: [],
      roleList: [],
      importUrl: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        year: [
          { required: true, message: "请选择年份", trigger: "change" },
        ],
        sCode: [
          { required: true, message: "请选择专业", trigger: "change" },
        ],
        feeType: [
          { required: true, message: "请选择收费标准", trigger: "change" },
        ],
        bedNum: [
          { required: true, message: "请填写床位数", trigger: "bulr" },
        ],
      },
    };
  },
  created() {
    this.getList();
     specialityList({ pageSize: 10000 }).then((response) => {
        this.typeList = response.rows;
      });
  },
  methods: {
    handleNodeClick(data) {
      console.log(data, "data");
      // this.queryParams.deptId = data.id;
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      feeTypeList(this.queryParams).then((response) => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
  onSearch() {
      // 查询条件和分页数据合并
      this.getList();
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    changeType(idnex){
     
      const selectedOption = this.typeList.find(item => item.sCode === idnex);
       console.log(selectedOption,'idnex')
       this.form.sName = selectedOption.name
       this.form.specialityId = selectedOption.id
    },
    handBedType(row){
      console.log(row,'shud')
    
     if(row.id) {
 this.classParams.typeId = row.id
     this.getListDate()
     }
 
    },
    getListDate(){
 feeTypeInfo(this.classParams).then(res=> {
        console.log(res,'dsdas')
        this.openDlg = true
         this.dataList = res.rows || [];
        this.dataTotal = res.total || 0;
      })
    },
     // 弹窗查询
      classQuery() {
      this.getListDate()
    },
    // 弹窗重置
    classReset() {
      this.classParams.registerCode = ''
      this.classParams.studentName = ''
      this.getListDate()

    },
     submitUpload() {
       // 使用防抖确保只提交一次
    if (!this.submitLock) {
      this.submitLock = true;
      this.$refs.uploads.submit();
      
      // 3秒后重置锁，防止长时间锁定
      setTimeout(() => {
        this.submitLock = false;
      }, 5000);
    }
     
      // this.$refs.uploads.clearFiles();
    },
       handleFileUploadProgress() {

      this.upload.isUploading = true;
    },
    onSuccess(response) {
      if (response.code == 200) {
        this.$message.success("文件上传成功");
        this.importUrl = response.url;
        this.upload.isUploading = false;
        this.$refs.uploads.clearFiles();
        this.upload.open = false;
        this.uploadData = true;
        this.getList();
      } else {
       
        this.upload.isUploading = false;
        this.$refs.uploads.clearFiles();
        this.upload.open = false;
        this.uploadData = true;
        this.$message.error(response.msg);
        // this.getList();
      }
    },
     /** 导出按钮操作 */
    handleExportTemplate() {
      this.download(
        "/dorm/feeType/downloadTemplate",
        {
          ...this.queryParams,
        },
        `宿舍收费类型设置分配模版${new Date().getTime()}.xlsx`
      );
    },
    importData() {
      let link = document.createElement("a");
      //创建一个a标签
      link.style.display = "none";
      //将a标签隐藏
      link.href = process.env.VUE_APP_BASE_API + this.importUrl;
      //给a标签添加下载链接  "域名+接口"  safe是一个动态的域名  后面的接口替换成你自己的下载接口
      link.setAttribute("download", "下载上传结果");
      // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
      document.body.appendChild(link);
      //将上面创建的a标签加入到body的尾部
      link.click();
      //执行a标签
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined,
        });
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.name = selection.map(item => item.name);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
     this.updatadisabled= false
      this.title = "新增公寓楼房间类型";
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.updatadisabled = true
      const roleId = row.id || this.ids;
      getFeeType(roleId).then((response) => {
        this.form = response.data;
        this.form.year = response.data.year+ '';
        this.form.feeType = response.data.feeType+ '';
        this.open = true;
        this.title = "修改公寓楼房间类型";
      });
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            putFeeType(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
        
            updateFeeType(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除数据项？')
        .then(function () {
          return delFeeType(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
        handleExport() {
          this.download(
        "/dorm/feeType/export",
        {
          ...this.queryParams,
        },
        `宿舍收费类型${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>